const app = getApp()
const { envList } = require('../../envList')
Page({
    data: {
        // 日期区间天
        days: [],
        // 周
        weeks: ['日', '一', '二', '三', '四', '五', '六'],
        // 加班请假记录
        record: [],
        // 加班费
        sumJbf: 0,
        // 加班总时长
        sumAll: 0,
        // 工作日加班时长
        sumGzr: 0,
        // 休息日加班时长
        sumXxr: 0,
        // 节假日加班时长
        sumJjr: 0,
        // 请假时长
        sumQj: 0,
        // 开始触摸时x轴坐标
        startClientX: Number,
        // 考勤周期开始日期
        startDate: Date,
        // 考勤周期结束日期
        endDate: Date,
        // 考勤周期开始日期字符串格式
        startDateFormat: String,
        // 考勤周期结束日期字符串格式
        endDateFormat: String
    },

    /**
     * 页面加载
     */
    onLoad() {
        // 定时器：200毫秒执行一次，直至小程序全局变量Load完成
        const Inter = setInterval(() => {
            if (app.globalData.IsLoad) {
                this.getDateRange(0);
                clearInterval(Inter);
            }
        }, 200)
    },

    /**
     * 计算考勤周期日期区间
     * @param {*} shift 0：当前日期区间；1：下个区间；-1：上个区间
     */
    getDateRange(shift) {
        const now = new Date();
        if (app.globalData.CycleId == 0) {
            switch (shift) {
                case 0:
                    this.data.startDate = new Date(now.getFullYear(), now.getMonth(), 1);// 获取当前月份开始日期
                    this.data.endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);// 获取当前月份结束日期
                    break;
                case 1:
                    this.data.startDate = new Date(this.data.endDate.setDate(this.data.endDate.getDate() + 1));// 根据结束日期+1天获取下月开始日期
                    this.data.endDate = new Date(this.data.startDate.getFullYear(), this.data.startDate.getMonth() + 1, 0);
                    break;
                case -1:
                    this.data.endDate = new Date(this.data.startDate.setDate(this.data.startDate.getDate() - 1));
                    this.data.startDate = new Date(this.data.endDate.getFullYear(), this.data.endDate.getMonth(), 1);
                    break;
            }
        } else {
            let startMonth;// 周期开始日期月份
            let endMonth;// 周期结束日期月份
            let startYear;// 周期开始日期年份
            let endYear;// 周期结束日期年份
            let startDate = app.globalData.CycleId + 1;
            let endDate = app.globalData.CycleId;
            let startTotalDays;
            let endTotalDays;
            switch (shift) {
                case 0:
                    if (now.getDate() > app.globalData.CycleId) {
                        startMonth = now.getMonth() + 1;
                        endMonth = startMonth >= 12 ? 1 : (startMonth + 1);
                        startYear = now.getFullYear();
                        endYear = endMonth == 1 ? (startYear + 1) : startYear;
                    } else {
                        endMonth = now.getMonth() + 1;
                        startMonth = endMonth == 1 ? 12 : (endMonth - 1);
                        endYear = now.getFullYear();
                        startYear = startMonth == 12 ? (endYear - 1) : endYear;
                    }
                    break;
                case 1:
                    let tempEndDate = new Date(this.data.endDate);
                    this.data.startDate = new Date(tempEndDate.setDate(tempEndDate.getDate() + 1));
                    endMonth = this.data.endDate.getMonth() >= 11 ? 1 : this.data.endDate.getMonth() + 2;
                    endYear = endMonth == 1 ? this.data.endDate.getFullYear() + 1 : this.data.endDate.getFullYear();
                    break;
                case -1:
                    this.data.endDate = new Date(this.data.startDate.setDate(this.data.startDate.getDate() - 1));
                    startMonth = this.data.endDate.getMonth() == 0 ? 12 : this.data.endDate.getMonth();
                    startYear = startMonth == 12 ? this.data.endDate.getFullYear() - 1 : this.data.endDate.getFullYear();
                    break;
            }
            if (startMonth && startYear) {
                startTotalDays = new Date(startYear, startMonth, 0).getDate();
                if (startTotalDays < startDate) {
                    startDate = 1
                    startMonth = this.data.endDate.getMonth() + 1;
                    startYear = this.data.endDate.getFullYear();
                }
                this.data.startDate = new Date(startYear, startMonth - 1, startDate);
            }
            if (endMonth && endYear) {
                endTotalDays = new Date(endYear, endMonth, 0).getDate();
                if (endTotalDays < endDate) {
                    endDate = endTotalDays;
                }
                this.data.endDate = new Date(endYear, endMonth - 1, endDate);
            }
        }
        this.setData({
            startDateFormat: this.data.startDate.getFullYear() + '-' + (this.data.startDate.getMonth() + 1) + '-' + this.data.startDate.getDate(),
            endDateFormat: this.data.endDate.getFullYear() + '-' + (this.data.endDate.getMonth() + 1) + '-' + this.data.endDate.getDate()
        })
        this.drowCalendar();
    },

    /**
     * 根据日期区间画日历
     */
    drowCalendar() {
        // 获取开始日期是周几
        let startDay = this.data.startDate.getDay();
        // 获取结束日期是周几
        let endDay = this.data.endDate.getDay();
        var tempDate = this.data.startDate.getTime() - 24 * 60 * 60 * 1000 * startDay;
        var days = [];
        while (tempDate <= this.data.endDate.getTime() + 24 * 60 * 60 * 1000 * (6 - endDay)) {
            const dayItem = {
                date: null,
                day: null,
                dateType: null,
                jb: null,
                qj: null
            }
            if (tempDate >= this.data.startDate.getTime() && tempDate <= this.data.endDate.getTime()) {
                dayItem.time = tempDate;
                dayItem.day = new Date(tempDate).getDate();
                dayItem.dateType = 0;
                dayItem.jb = '--';
                dayItem.qj = '--';
            }
            days.push(dayItem);
            tempDate += 24 * 60 * 60 * 1000;
        }
        this.setData({
            days: days
        });
        this.getRecord();
    },

    /**
     * 获取当前日期区间加班记录
     */
    async getRecord() {
        const db = wx.cloud.database({ env: envList[1].envId });
        const _ = db.command
        const collection = db.collection('WorkRecord');
        await collection.where({
            _openid: app.globalData.openId,
            Date: _.gte(this.data.startDate).and(_.lte(this.data.endDate))
        }).get().then(res => {
            this.data.record = res.data;
        })
        if (this.data.record.length == 20) {
            await collection.where({
                _openid: app.globalData.openId,
                Date: _.gte(this.data.startDate).and(_.lte(this.data.endDate))
            }).skip(20).get().then(res => {
                this.data.record = this.data.record.concat(res.data);
            })
        }
        this.writeRecord();
    },

    /**
     * 把加班记录写进日历
     */
    writeRecord() {
        this.data.days.forEach(day => {
            const recordItem = this.data.record.find(p => p.Date.getDate() == day.day);
            if (recordItem) {
                day.jb = recordItem.JbHour == '0' ? '--' : recordItem.JbHour;
                day.qj = recordItem.QjHour == '0' ? '--' : recordItem.QjHour;
                day.dateType = recordItem.DayType;
            } else {
                day.dateType = 0;
                day.jb = '--';
                day.qj = '--';
            }
        });
        this.setData({
            days: this.data.days
        })
        let sumGzr = 0;
        let sumXxr = 0;
        let sumJjr = 0;
        let sumQj = 0;
        this.data.record.forEach(p => {
            sumQj += p.QjHour;
            if (p.DayType == 0) {
                sumGzr += p.JbHour;
            } else if (p.DayType == 1) {
                sumXxr += p.JbHour;
            } else if (p.DayType == 2) {
                sumJjr += p.JbHour;
            }
        })
        this.setData({
            sumJbf: sumGzr * app.globalData.GzrMoney + sumXxr * app.globalData.XxrMoney + sumJjr * app.globalData.JjrMoney,
            sumAll: sumGzr + sumXxr + sumJjr - sumQj,
            sumGzr: sumGzr,
            sumXxr: sumXxr,
            sumJjr: sumJjr,
            sumQj: sumQj
        })
    },

    /**
     * 页面显示
     */
    onShow() {
        if (app.globalData.IsUpdate) {
            this.getDateRange(0);
        } else if (app.globalData.IsLoad) {
            this.getRecord();
        }
    },

    // changeMonth(flag) {
    //     if (flag) {
    //         this.getDateRange(1);
    //     } else {
    //         this.getDateRange(-1);
    //     }
    //     this.drowCalendar();
    // },

    /**
     * 日期点击事件
     * @param {*} e 
     */
    inpRecord(e) {
        const dayItem = e.currentTarget.dataset.dayitem;
        // 进入当前日期加班记录录入界面
        wx.navigateTo({
            url: '../inpRecord/inpRecord?time=' + dayItem.time + '&jbHour=' + dayItem.jb + '&qjHour=' + dayItem.qj + '&dateType=' + dayItem.dateType
        })
    },

    /**
     * 触摸开始事件
     * @param {*} e 
     */
    touchstart(e) {
        this.setData({
            startClientX: e.changedTouches[0].clientX
        })
    },

    /**
     * 触摸结束事件
     * @param {*} e 
     */
    touchend(e) {
        if (e.changedTouches[0].clientX - this.data.startClientX > 100) {
            this.getDateRange(-1);
        }
        if (this.data.startClientX - e.changedTouches[0].clientX > 100) {
            this.getDateRange(1);
        }
    }
})

// 1.修改保存周期改成若没修改，则不用操作数据库，加班薪资同理
// 2.修改数据库字段，需要有日期字段===
// 3.根据日期区间获取加班记录，匹配到相应的日期===
// 4.页面传参，年月日改为日期===
// 5.首页样式修改===
// 6.首页显示日期区间===
// 7.左右滑动修改日期区间改为按钮===
// 8.彩蛋：文章列表
// 9.问题反馈和查看问题反馈
// 10.计算加班工资
